import { KeywordModel } from '../../models/keyword.js';
import { BookModel } from '../../models/book.js';
import { paginationBev } from '../behaviors/pagination.js';

const keywordModel = new KeywordModel();
const bookModel = new BookModel();

Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBev],

  properties: {
    more: {
      type: String,
      observer: 'loadMore'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    searching: false,
    q: '',
    loading: false,
    loadingCenter: false,
    noMore: false
  },

  attached() {
    this.setData({
      historyWords: keywordModel.getHistory()
    })

    keywordModel.getHot().then(res => {
      this.setData({
        hotWords: res.hot
      })
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    loadMore: function() {
      if(!this.data.q) {
        return
      }
      if (this.isLocked()) {
        return
      }
      if (this.hasMore()) {
        this.locked();
        bookModel.search(this.getCurrentStart(), this.data.q).then(res => {
          this.setMoreData(res.books);
          this.unLocked();
        },() => {
          this.unLocked();
        })
      }else {
        this.setData({
          noMore: true
        })
      }
    },

    onCancel: function (event) {
      this.initialize();
      this.triggerEvent('cancel', {}, {})
    },

    onDelete: function (event) {
      this.initialize();
      this._closeResult();
      this.setData({
        q: '',
        noMore: false
      })
    },

    onConfirm: function (event) {
      const q = event.detail.value || event.detail.text;
      if(!q) {
        wx.showToast({
          title: '您没有输入书籍名',
          icon: 'none'
        })
        return
      }
      this._showLoadingCenter();
      this._showResult();
      this.setData({
        q: q
      })
      bookModel.search(0, q).then(res => {
        this.setMoreData(res.books);
        this.setTotal(res.total);
        keywordModel.addToHistory(q);
        this._hideLoadingCenter();
      })
    },

    _showLoadingCenter() {
      this.setData({
        loadingCenter: true
      })
    },

    _hideLoadingCenter() {
      this.setData({
        loadingCenter: false
      })
    },

    _showResult: function () {
      this.setData({
        searching: true
      })
    },

    _closeResult: function () {
      this.setData({
        searching: false
      })
    }
  }
})
